package com.alstudio.ui.module.voip;

import java.io.File;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.core.voip.CallState;
import com.alstudio.core.voip.VoipCallIconState;
import com.alstudio.core.voip.ALVoipCallManager;
import com.alstudio.core.voip.VoipLocalTimeCallback;
import com.alstudio.module.ALModuleManager;
import com.alstudio.module.voip.ALPostToRtpServerData;
import com.alstudio.module.voip.ALVoipEvent;
import com.alstudio.module.voip.ALVoipEventType;
import com.alstudio.module.voip.ALVoipModuleManager;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALPhoto;
import com.alstudio.module.xmpp.protocol.xmpp.packact.ALMessage;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.pojo.module.user.User;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.utils.android.color.ALColorUtils;
import com.alstudio.utils.android.net.ALConnectionManager;
import com.alstudio.utils.android.net.http.UploadPhotoRequest;
import com.alstudio.utils.asyncTask.ALAsycTask;
import com.alstudio.utils.asyncTask.ALAsyncTaskCallback;
import com.alstudio.utils.chat.ALChatViewManager;
import com.alstudio.utils.chat.ALChatViewManagerWorkingStateListener;
import com.alstudio.utils.formater.time.ALTimeUtils;
import com.alstudio.utils.image.BitmapUtil;
import com.alstudio.utils.log.ALLog;
import com.alstudio.utils.user.UserIconsUtil;
import com.alstudio.view.PageIndicator;
import com.alstudio.view.ViewUtils;
import com.alstudio.view.dialog.AlertDialogCreator;
import com.alstudio.view.listener.AlDialogOnClickListener;
import com.alstudio.view.viewpagerextend.ALViewpagerCreator;
import com.alstudio.view.viewpagerextend.MyViewPager;
import com.loovee.imaohu.R;

public class CallActivity extends TitleBarActivity implements
		OnPageChangeListener, ALChatViewManagerWorkingStateListener,
		VoipLocalTimeCallback {

	private ALMessage intentMsg = null;
	// 判断通话是否已经建立
	private boolean isIncommingCall = false;
	// 通话状态，缺省为呼出电话
	private CallState callState = CallState.CALL_OUTGOING;
	// 通话用户
	private User user;
	private PageIndicator mPageIndicator;
	private ALViewpagerCreator viewPagerCreator;

	private View userInfo, userChat, center_view;

	private ArrayList<View> views = new ArrayList<View>();
	private MyViewPager viewPager;

	// 对方
	private ImageView userIcon;
	private TextView nick, age_location, glamour_count, fans_count, call_price,
			chat_desc;
	private LinearLayout img_layout;
	// 聊天的总布局
	private LinearLayout chat_content;

	// 播放对方大图头像
	private ViewFlipper flipper;

	private VoipCallIconState mIconState;

	private boolean isMuted = false;

	private ALChatViewManager chatViewManager;

	private boolean isActivied = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initData();
		setupView(this, getClass().getSimpleName());
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		intentMsg = (ALMessage) getIntent().getSerializableExtra("msg");
		if (intentMsg == null) {
			intentMsg = ALVoipCallManager.getDefaultALVoipManager()
					.getCallSession();
			if (intentMsg == null) {
				return;
			}
		}
		// 监听通话时间回调
		ALVoipCallManager.getDefaultALVoipManager()
				.setVoipLocalCallingTimeCallback(this);
		// 获取本地calling time
		callingTime = ALVoipCallManager.getDefaultALVoipManager()
				.getLocalTime();
		mIconState = ALVoipCallManager.getDefaultALVoipManager()
				.getCallIconState();
		isMuted = mIconState.isMuted();
		user = (User) intentMsg.getData();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (!isUIinited) {
			// isUIinited = true;
			ALVoipCallManager.getDefaultALVoipManager()
					.removeOutGoingCallNotification();
			ALVoipCallManager.getDefaultALVoipManager()
					.removeInCommingCallNotification();
			ALVoipCallManager.getDefaultALVoipManager()
					.removeInCallNotification();
			ALVoipCallManager.getDefaultALVoipManager()
					.removeNewCallChatMsgNotification();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);
		setTitleBarActivityContentView(R.layout.call_activity);
		hideTitleBar();
		flipper = (ViewFlipper) findViewById(R.id.flipper);
		mPageIndicator = (PageIndicator) findViewById(R.id.page_indicator);
		mPageIndicator.setDotCount(3);
		mPageIndicator.setDotDrawable(getResources().getDrawable(
				R.drawable.call_activity_dot));

		setViewOnclickListener(R.id.buttonAccept, this);
		setViewOnclickListener(R.id.buttonReject, this);
		setViewOnclickListener(R.id.speaker, this);
		setViewOnclickListener(R.id.mute, this);
		setViewOnclickListener(R.id.handup, this);

		setViewOnclickListener(R.id.btn_opt, this);
		setViewOnclickListener(R.id.btn_back, this);

		initViewPager();
		initViewFlipper();
		setNick();

		if (intentMsg.getType() == ALMessage.NEW_INCOMMING_CALL) {
			isIncommingCall = true;
		} else {
		}

		if (isIncommingCall) {
			// 新来电
			// 隐藏接通后的按钮
			goneView(R.id.oncall_btn_layout);
			showView(R.id.incomming_call_btn_layout);
		} else {
			// 拨打电话
			goneView(R.id.incomming_call_btn_layout);
		}
		updateCallState(ALVoipCallManager.getDefaultALVoipManager()
				.getCurrentState());

		setCallIcon();

		updateCallStateColor();
	}

	private void setCallIcon() {
		if (isMuted) {
			findViewById(R.id.mute_icon).setBackgroundResource(
					R.drawable.call_bottom_mute_on);
			findViewById(R.id.mute_txt).setBackgroundResource(
					R.drawable.call_bottom_mute_form);
		} else {
			findViewById(R.id.mute_icon).setBackgroundResource(
					R.drawable.call_bottom_mute);
			findViewById(R.id.mute_txt).setBackgroundResource(
					R.drawable.call_bottom_mute_form_un);
		}

		if (ALLocalEnv.getLocalEnv().getVoipMediaManager().isSpeakerOn()) {
			findViewById(R.id.speaker_icon).setBackgroundResource(
					R.drawable.call_bottom_voice_on);
			findViewById(R.id.speaker_txt).setBackgroundResource(
					R.drawable.call_bottom_voice_form);
		} else {
			findViewById(R.id.speaker_icon).setBackgroundResource(
					R.drawable.call_bottom_voice);
			findViewById(R.id.speaker_txt).setBackgroundResource(
					R.drawable.call_bottom_voice_form_un);
		}
	}

	/**
	 * 初始化ViewPager
	 */
	private void initViewPager() {
		viewPager = (MyViewPager) findViewById(R.id.view_pager);

		userInfo = ALLocalEnv.getLocalEnv().getGlobalLayoutInflater()
				.inflate(R.layout.call_user_info_layout, null);
		userIcon = (ImageView) userInfo.findViewById(R.id.icon);
		nick = (TextView) userInfo.findViewById(R.id.nick);
		img_layout = (LinearLayout) userInfo.findViewById(R.id.img_layout);
		age_location = (TextView) userInfo.findViewById(R.id.age_location);
		glamour_count = (TextView) userInfo.findViewById(R.id.glamour_count);
		fans_count = (TextView) userInfo.findViewById(R.id.fans_count);
		call_price = (TextView) userInfo.findViewById(R.id.call_price);

		userInfo.findViewById(R.id.user_info_to_right).setOnClickListener(this);

		// 聊天布局
		userChat = ALLocalEnv.getLocalEnv().getGlobalLayoutInflater()
				.inflate(R.layout.call_user_chat, null);
		// 无聊天信息时的提示
		chat_desc = (TextView) userChat.findViewById(R.id.chat_desc);
		// 聊天内容区
		chat_content = (LinearLayout) userChat.findViewById(R.id.chat_content);
		// 设置点击事件
		userChat.findViewById(R.id.chat_to_left).setOnClickListener(this);
		userChat.findViewById(R.id.take_photo).setOnClickListener(this);
		userChat.findViewById(R.id.clear_screen).setOnClickListener(this);
		// 缺省禁止快照清屏点击
		userChat.findViewById(R.id.clear_screen).setEnabled(false);
		userChat.findViewById(R.id.take_photo).setEnabled(false);

		center_view = ALLocalEnv.getLocalEnv().getGlobalLayoutInflater()
				.inflate(R.layout.user_call_empty, null);
		center_view.findViewById(R.id.empty_to_left).setOnClickListener(this);
		center_view.findViewById(R.id.empty_to_right).setOnClickListener(this);

		views.add(userInfo);
		views.add(center_view);
		views.add(userChat);

		viewPagerCreator = new ALViewpagerCreator(ALLocalEnv.getLocalEnv()
				.getGlobalLayoutInflater(), null, views);
		viewPagerCreator.setViewPager(viewPager);
		viewPagerCreator.addOnPageChangeListener(this);
		viewPagerCreator.commit(1);

		showCallUserInfo();
		initChatContainer();
	}

	/**
	 * 显示用户资料
	 */
	private void showCallUserInfo() {

		ALLocalEnv.getLocalEnv().displayImagePluginServerlet(user.getAvatar(),
				userIcon,
				ALLocalEnv.getLocalEnv().getCycleImageDisplayOptions());
		nick.setText(ALLocalEnv.getLocalEnv().getMyProfile().getNick());
		age_location.setText(user.getAge() + " " + user.getProvince());

		UserIconsUtil.setupIconsLayout(img_layout, user);
		String callPrice = user.getCallPrice();
		if (TextUtils.isEmpty(user.getCallPrice())) {
			// 免费
			callPrice = getString(R.string.TxtFree);
		}
		call_price.setText(callPrice);
		glamour_count.setText(user.getGlamour());
		fans_count.setText(user.getCollectingnum());
	}

	/**
	 * 初始化用户大图轮播控件
	 */
	private void initViewFlipper() {

		if (user.getPhotos().size() > 1) {
			for (int i = 0; i < user.getPhotos().size(); i++) {
				ALPhoto photo = user.getPhotos().get(i);
				ImageView iv = new ImageView(ALLocalEnv.getLocalEnv());
				iv.setBackgroundResource(R.drawable.personal_default_bg);
				iv.setScaleType(ScaleType.CENTER_CROP);
				flipper.addView(iv, new LayoutParams(LayoutParams.FILL_PARENT,
						LayoutParams.FILL_PARENT));
				ALLocalEnv.getLocalEnv().displayImagePluginServerlet(
						photo.getPicFileid(), iv,ALLocalEnv.getLocalEnv().getLargeIconImageDisplayOption());
			}
			flipper.setInAnimation(this, android.R.anim.fade_in);
			flipper.setOutAnimation(this, android.R.anim.fade_out);
			flipper.startFlipping();
		}
	}

	/**
	 * 初始化聊天布局区
	 */
	private void initChatContainer() {
		chatViewManager = new ALChatViewManager(ALLocalEnv.getLocalEnv()
				.getGlobalLayoutInflater(), chat_content, this);
		chatViewManager.setALChatViewWorkingStateListener(this);

		if (ALVoipCallManager.getDefaultALVoipManager().getChatMsgs().size() > 0) {
			// 之前有聊天消息的，重新加吧
			startReloadCallImageMessage(ALVoipCallManager
					.getDefaultALVoipManager().getChatMsgs());
		}

	}

	@Override
	public void handleUserAcceptCallEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleUserAcceptCallEvent(msg);
		updateCallState(CallState.CALL_ESTABLISED);
		prepareStartStream(msg);
	}

	@Override
	public void handleUserHandupEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleUserHandupEvent(msg);
		updateCallState(CallState.CALL_HANDUP);
		invokeClearActivityEnv();

		// 停止语音传输
		ALVoipEvent event = new ALVoipEvent();
		event.setEventType(ALVoipEventType.ALVOIP_EVENT_STOP_STREAM_TO_REMOTE_USER);

		ALModuleManager.getDefaultModuleManager().postEventToModuleManager(
				event);
	}

	@Override
	public void invokeClearActivityEnv() {
		// TODO Auto-generated method stub
		super.invokeClearActivityEnv();
		if (flipper != null) {
			flipper.stopFlipping();
			flipper.removeAllViews();
		}
	}

	@Override
	public void handleUserRejectCallEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleUserRejectCallEvent(msg);
		// callState = CallState.CALL_REJECT;
		updateCallState(CallState.CALL_REJECT);
		// finish();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.buttonAccept:
			// 接通电话
			doAccept();
			break;
		case R.id.buttonReject:
			// 拒绝来电
			doReject();
			break;
		case R.id.handup:
			// 挂断电话
			doHandUp();
			break;
		case R.id.speaker:
			if (!isActivied)
				return;
			changeSpeaker();
			break;
		case R.id.mute:
			if (!isActivied)
				return;
			invokeMuteAction();
			break;
		case R.id.take_photo:
			// 快照
			if (!isActivied)
				return;
			showPhotoProcessDialog(false);
			break;
		case R.id.clear_screen:
			// 清屏
			if (!isActivied)
				return;
			invokeClearScreen();
			break;
		case R.id.empty_to_left:
		case R.id.chat_to_left:
			viewPagerToPrevious();
			break;
		case R.id.empty_to_right:
		case R.id.user_info_to_right:
			viewPagerToNext();
			break;
		case R.id.btn_opt:
			// 拉黑
			showInvokeBlaickListDialog();
			break;
		case R.id.btn_back:
			// 关闭界面
			finish();
			break;
		}
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		// 移除时间回调
		ALVoipCallManager.getDefaultALVoipManager()
				.setVoipLocalCallingTimeCallback(null);
		mhandler.removeCallbacks(finishActivityTask);
		// mhandler.removeCallbacks(autoRejectTask);
		// ALLocalEnv.getLocalEnv().getVoipMediaManager().stopVoipRingtone();
		ALVoipCallManager.getDefaultALVoipManager().onALEvent(false);
	}

	/**
	 * 设定通话对方昵称
	 */
	private void setNick() {
		showTextMessage(R.id.caller, user.getNick());
	}

	private void updateCallStateText(int res) {
		showTextMessage(R.id.call_state_txt, res);
		updateCallStateColor();
	}

	private void updateCallStateColor() {
		switch (callState) {
		case CALL_DISCONNECT:
		case CALL_HANDUP:
		case CALL_REJECT:
			setTextColor(R.id.call_state_txt, ALColorUtils.getColor(
					getApplicationContext(), R.color.call_reject));
			ViewUtils.setBackgroundRes(findViewById(R.id.call_state_icon),
					R.drawable.call_icon_red);
			break;
		case CALL_ESTABLISED:
		case CALL_INCOMMING:
		case CALL_OUTGOING:
			setTextColor(R.id.call_state_txt, ALColorUtils.getColor(
					getApplicationContext(), R.color.call_establised));
			ViewUtils.setBackgroundRes(findViewById(R.id.call_state_icon),
					R.drawable.call_icon_green);
			break;
		default:
			break;
		}
	}

	/**
	 * 更新通话状态
	 * 
	 * @param newState
	 */
	private void updateCallState(CallState newState) {
		callState = newState;
		switch (callState) {
		case CALL_DISCONNECT:
			isActivied = false;
			ALVoipCallManager.getDefaultALVoipManager().onCallStateChanged(
					CallState.CALL_DISCONNECT, null);
			break;
		case CALL_ESTABLISED:
			// mhandler.removeCallbacks(autoRejectTask);
			// 调整音量
			ALLocalEnv.getLocalEnv().getVoipMediaManager().setMaxVoiceVolume();
			isActivied = true;
			showCallingTime();
			userChat.findViewById(R.id.clear_screen).setEnabled(true);
			userChat.findViewById(R.id.take_photo).setEnabled(true);
			// 隐藏接听、拒绝布局
			goneView(R.id.incomming_call_btn_layout);
			// 显示接通后的扬声器、静音、挂断布局
			showView(R.id.oncall_btn_layout);
			break;
		case CALL_HANDUP:
			// 不在接收几时消息啦
			ALVoipCallManager.getDefaultALVoipManager()
					.setVoipLocalCallingTimeCallback(null);
			updateCallStateText(R.string.TxtCallend);
			isActivied = false;
			// 1秒后关闭
			mhandler.postDelayed(finishActivityTask, ALTimeUtils.SECOND);
			break;
		case CALL_INCOMMING:
			setNick();
			updateCallStateText(R.string.TxtIncommingCall);
			goneView(R.id.oncall_btn_layout);
			showView(R.id.incomming_call_btn_layout);
			// mhandler.postDelayed(autoRejectTask, ACCEPT_TIMEOUT);
			break;
		case CALL_OUTGOING:
			setNick();
			updateCallStateText(R.string.TxtCalling);
			ALVoipCallManager.getDefaultALVoipManager().onCallStateChanged(
					CallState.CALL_OUTGOING, intentMsg);
			goneView(R.id.incomming_call_btn_layout);
			break;
		case CALL_REJECT:
			isActivied = false;
			updateCallStateText(R.string.TxtUserReject);
			mhandler.postDelayed(finishActivityTask, ALTimeUtils.SECOND);
			break;
		default:
			break;
		}
	}

	/********************************************* 点击事件 ****************************************************/
	/**
	 * 处理静音事件
	 */
	private void invokeMuteAction() {

		isMuted = !isMuted;

		if (isMuted) {
			findViewById(R.id.mute_icon).setBackgroundResource(
					R.drawable.call_bottom_mute_on);
			findViewById(R.id.mute_txt).setBackgroundResource(
					R.drawable.call_bottom_mute_form);
		} else {
			findViewById(R.id.mute_icon).setBackgroundResource(
					R.drawable.call_bottom_mute);
			findViewById(R.id.mute_txt).setBackgroundResource(
					R.drawable.call_bottom_mute_form_un);
		}

		ALLocalEnv.getLocalEnv().getVoipMediaManager().setMute(isMuted);

		ALVoipCallManager.getDefaultALVoipManager().getCallIconState()
				.setSpeaker(isMuted);
	}

	/**
	 * 处理扬声器、耳机切换事件
	 */
	private void changeSpeaker() {
		ALLocalEnv
				.getLocalEnv()
				.getVoipMediaManager()
				.setSpeakerState(
						!ALLocalEnv.getLocalEnv().getVoipMediaManager()
								.isSpeakerOn());
		if (ALLocalEnv.getLocalEnv().getVoipMediaManager().isSpeakerOn()) {
			findViewById(R.id.speaker_icon).setBackgroundResource(
					R.drawable.call_bottom_voice_on);
			findViewById(R.id.speaker_txt).setBackgroundResource(
					R.drawable.call_bottom_voice_form);
		} else {
			findViewById(R.id.speaker_icon).setBackgroundResource(
					R.drawable.call_bottom_voice);
			findViewById(R.id.speaker_txt).setBackgroundResource(
					R.drawable.call_bottom_voice_form_un);
		}

		ALVoipCallManager
				.getDefaultALVoipManager()
				.getCallIconState()
				.setSpeaker(
						ALLocalEnv.getLocalEnv().getVoipMediaManager()
								.isSpeakerOn());
	}

	/**
	 * 接听电话
	 */
	private void doAccept() {
		// callState = CallState.CALL_ESTABLISED;
		updateCallState(CallState.CALL_ESTABLISED);
		udpTest();
	}

	/**
	 * 拒绝来电
	 */
	private void doReject() {
		ALLog.d("拒绝 " + intentMsg.getFromNick() + " 的来电");

		ALVoipCallManager.getDefaultALVoipManager().rejectCall();
		finish();

	}

	/**
	 * 挂断电话
	 */
	private void doHandUp() {
		ALVoipCallManager.getDefaultALVoipManager().handupCall();
		updateCallState(CallState.CALL_HANDUP);
	}

	/**
	 * 处理清屏事件
	 */
	private void invokeClearScreen() {
		chatViewManager.clearAllChatMessage();
		ALVoipCallManager.getDefaultALVoipManager().clearChatMsg();
	}

	private void showInvokeBlaickListDialog() {
		if (!user.isInblacklist()) {
			AlertDialogCreator dialog = AlertDialogCreator
					.createTwoButtonNormalDialog(this, false);
			dialog.setMessage(getString(R.string.TxtAddBlackListHint));
			dialog.setLeftKeyListener(new AlDialogOnClickListener() {

				@Override
				public void onClick() {
					// TODO Auto-generated method stub
					invokeBlackListOpt();
				}
			});
			dialog.showDialog();
			return;
		}
		invokeBlackListOpt();
	}

	/**
	 * 处理黑名单
	 */
	private void invokeBlackListOpt() {
		if (!ALLocalEnv.isSendXmppDataEnable())
			return;
		if (user.isInblacklist()) {
			ALLog.d("将" + user.getNick() + "移出黑名单");
			ALLocalEnv.getLocalEnv().getDatabase()
					.deleteUserFromBlackList(user.getJid());
			user.setInblacklist(false);
		} else {
			ALLog.d("将" + user.getNick() + "加入黑名单");
			ALLocalEnv.getLocalEnv().getDatabase().insertUserToBlackList(user);
			user.setInblacklist(true);
			if (user.isFavorite()) {
				// 已經收藏，現在要取消收藏
				ALUiXmppRequestCreator.postALUiXmppDeleteFriendOrFans(
						ALUiXmppRequestCreator.REQUEST_DELETE_USER_FAVORITES,
						user.getJid());
			}

			if (user.isFans()) {
				// 移除粉絲
				ALUiXmppRequestCreator.postALUiXmppDeleteFriendOrFans(
						ALUiXmppRequestCreator.REQUEST_DELET_USER_FANS,
						user.getJid());
			}

		}

		new Thread() {
			public void run() {
				ArrayList<User> users = ALLocalEnv.getLocalEnv().getDatabase()
						.getBlackListUsers();
				ALUiXmppRequestCreator.postALUiXmppBlackListFun(
						ALUiXmppRequestCreator.REQUEST_ADD_USER_TO_BLACKLIST,
						users);
			};
		}.start();

		if (ALVoipCallManager.getDefaultALVoipManager().getCurrentState() == CallState.CALL_ESTABLISED
				|| !isIncommingCall) {
			// 通话已建立或者是去电，直接挂断
			doHandUp();
		} else {
			// 否则拒绝
			doReject();
		}
	}

	@Override
	public void handleAcceptCallEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleAcceptCallEvent(data);
		if (data.getResponseCode() == ALXmppEvent.RESPONSE_OK) {

			ALLocalEnv.getLocalEnv().getMediaManager().stopPlay();
			prepareStartStream(data.getMessage());
			updateCallState(CallState.CALL_ESTABLISED);

		} else {
			Toast.makeText(this, "无法接通", Toast.LENGTH_SHORT).show();
			ALVoipCallManager.getDefaultALVoipManager().onCallStateChanged(
					CallState.CALL_DISCONNECT, null);
			finish();
		}
	}

	@Override
	public void handleNewCallImageMessageEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleNewCallImageMessageEvent(msg);
		if (!isReloadMessage) {
			chatViewManager.showChatMessage(msg);
			viewPagerToLast();
		} else {
			// 正在读取聊天记录
			newChatMsgs.add(msg);
		}
	}

	/**
	 * 与RTP服务器交互，确定本地网络地址
	 */
	private void udpTest() {

		String user = ALLocalEnv.adapter.getXmppData().getUsername();
		ALPostToRtpServerData data = ALVoipModuleManager
				.getPostToRtpServerData(user, getIp(), 4000,
						ALConnectionManager.getConnectionTypeString(),
						ALVoipModuleManager.DEFAULT_RTP_SERVER_IP,
						ALVoipModuleManager.DEFAULT_RTP_SERVER_PORT);

		ALVoipEvent event = new ALVoipEvent();
		event.setData(data);
		event.setEventType(ALVoipEventType.ALVOIP_EVENT_POST_DATA_TO_RTP_SERVER);

		ALModuleManager.getDefaultModuleManager().postEventToModuleManager(
				event);
	}

	/**
	 * 开始打洞
	 * 
	 * @param msg
	 */
	private void prepareStartStream(ALMessage msg) {

		ALVoipEvent event = new ALVoipEvent();
		event.setData(ALVoipModuleManager.almessageToPostToRemoteUserData(msg));
		event.setEventType(ALVoipEventType.ALVOIP_EVENT_POST_DATA_TO_REMOTE_USER);

		ALModuleManager.getDefaultModuleManager().postEventToModuleManager(
				event);
	}

	/**
	 * 接收VOIP模块事件
	 * 
	 * @param event
	 */
	public void onALEvent(ALVoipEvent event) {
		if (!isActivityOn()) {
			return;
		}
		switch (event.getEventType()) {
		case ALVOIP_EVENT_POST_DATA_TO_RTP_SERVER_SUCCESS:
			ALUiXmppRequestCreator.postALUiXmppAcceptCall(intentMsg
					.getVoipSession());
			break;
		case ALVOIP_EVENT_POST_DATA_TO_RTP_SERVER_FAIL:
			break;
		case ALVOIP_EVENT_START_STREAM_TO_REMOTE_USER:
			ALLocalEnv.getLocalEnv().getVoipMediaManager().stopVoipRingtone();
			break;
		case ALVOIP_EVENT_STOP_STREAM_TO_REMOTE_USER:
			break;
		default:
			break;
		}
	}

	// 通话时间
	private long callingTime = 0;

	private void showCallingTime() {
		showTextMessage(R.id.call_state_txt,
				ALTimeUtils.formatTimeWithHour(callingTime));
	}

	private Runnable finishActivityTask = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			finish();
		}
	};

	/************************************** 上传图片 *********************************************/
	@Override
	protected void onGetProcessPhotosResult(String path, String name) {
		// TODO Auto-generated method stub
		super.onGetProcessPhotosResult(path, name);
		Uri uri = Uri.fromFile(new File(path));
		ALLog.d("得到图片路径" + uri.toString());

		ALMessage msg = ALLocalEnv.getLocalEnv().createMessage(user);
		msg.setType(ALMessage.CALL_IMAGE_MSG);
		msg.setFromAvatar(ALLocalEnv.getLocalEnv().getMyProfile()
				.getThumbAvatar());
		msg.setFilePath(path);
		msg.setBob(createBitmapBase64String(path));
		chatViewManager.showChatMessage(msg);

		ALVoipCallManager.getDefaultALVoipManager().onNewCallChatMsgReceived(
				msg);

		if (ALLocalEnv.isSendXmppDataEnable()) {
			// 上传图片
			uploadPic(path);
			showLoadingProgress();
		}
	}

	@Override
	protected void handleUploadPicSuccess(UploadPhotoRequest sender,
			String pictureFileId, String thumbFileId) {
		// TODO Auto-generated method stub
		super.handleUploadPicSuccess(sender, pictureFileId, thumbFileId);
		dismissLoadingProgress();

		ALMessage msg = ALLocalEnv.getLocalEnv().createMessage(user,
				ALMessage.CALL_IMAGE_MSG);
		msg.setFileId(pictureFileId);
		msg.setBob(createBitmapBase64String(sender.getFilepath()));
		ALUiXmppRequestCreator.postALUiXmppSendMessage(msg);
	}

	private String createBitmapBase64String(String filePath) {
		String base64 = "";
		Bitmap bm = BitmapUtil.decodeSampledBitmapFromFile(filePath, 120, 120);
		if (bm != null) {
			ALLog.d("得到图片大小 " + bm.getWidth() + " " + bm.getHeight());
			base64 = BitmapUtil.compressImagebybase64(bm);
			try {
				bm.recycle();
				bm = null;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return base64;
	}

	/******************************** viewpager 滑动事件 ******************************************************/
	// 当前位置
	private int currentItem = 0;

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int arg0) {
		// TODO Auto-generated method stub
		setActivePage(arg0);
	}

	/**
	 * viewpager切换后更新底部dot
	 * 
	 * @param page
	 */
	private void setActivePage(int page) {
		mPageIndicator.setActiveDot(page);
		currentItem = page;
	}

	private void viewPagerToNext() {
		viewPager.setCurrentItem(currentItem++, true);
	}

	private void viewPagerToPrevious() {
		viewPager.setCurrentItem(currentItem--, true);
	}

	private void viewPagerToLast() {
		viewPager.setCurrentItem(viewPager.getChildCount(), true);
	}

	/************************************ 聊天管理器事件 **********************************************/
	@Override
	public void onViewAdd() {
		// TODO Auto-generated method stub
		ViewUtils.goneView(chat_desc);
	}

	@Override
	public void onViewDelete() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onAllViewDelete() {
		// TODO Auto-generated method stub
		ViewUtils.showView(chat_desc);
	}

	private boolean isReloadMessage = false;

	private ArrayList<ALMessage> tmpChatMsgs;

	private ArrayList<ALMessage> newChatMsgs = new ArrayList<ALMessage>();

	private ALAsyncTaskCallback reloadCallImageMessageCallback = new ALAsyncTaskCallback() {

		@Override
		public Object onTaskStart(Object obj) {
			// TODO Auto-generated method stub

			if (tmpChatMsgs != null && tmpChatMsgs.size() > 0) {
				for (final ALMessage msg : tmpChatMsgs) {
					mhandler.post(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							chatViewManager.showChatMessage(msg);
						}
					});
				}
				tmpChatMsgs.clear();
				tmpChatMsgs = null;
			}

			return null;
		}

		@Override
		public Object onTaskFinish(Object obj) {
			// TODO Auto-generated method stub
			isReloadMessage = false;
			if (newChatMsgs.size() > 0) {
				startReloadCallImageMessage(newChatMsgs);
				newChatMsgs.clear();
				ALLog.d("重新读取未加入的消息");
			}
			return null;
		}

		@Override
		public Object onTaskCancel() {
			// TODO Auto-generated method stub
			return null;
		}
	};

	/**
	 * 开始保存系统消息
	 * 
	 * @param msg
	 */
	private void startReloadCallImageMessage(ArrayList<ALMessage> msgs) {
		isReloadMessage = true;
		tmpChatMsgs = new ArrayList<ALMessage>();
		tmpChatMsgs.addAll(msgs);
		ALAsycTask reloadCallImageMessageTask = new ALAsycTask(
				reloadCallImageMessageCallback);
		reloadCallImageMessageTask.execute(tmpChatMsgs);
	}

	/********************************************* 通话时间管理 *****************************************************/

	@Override
	public void onTimeChanged(int time) {
		// TODO Auto-generated method stub
		callingTime = time;
		showCallingTime();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.core.voip.VoipLocalTimeCallback#onAcceptTimeout()
	 */
	@Override
	public void onAcceptTimeout() {
		// TODO Auto-generated method stub
		finish();
	}

}
